package logger

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"goScaffold/settings"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

func Init(logConfig *settings.LogConfig) (err error) {
	//1、Encoder
	encoder := getEncoder()

	//2、WriterSyncer
	writeSyncer := getLogWriter(logConfig.Filename, logConfig.MaxSize, logConfig.MaxBackups, logConfig.MaxAge, logConfig.Compress)

	//3、日志级别
	var l = new(zapcore.Level)
	err = l.UnmarshalText([]byte(logConfig.Level)) //把配置文件中的字符串，反序列化成为zap中的Level类型
	if err != nil {
		return fmt.Errorf("获取配置文件中，日志级别失败，err:%w", err)
	}

	//4、创建zapcore.Core
	core := zapcore.NewCore(encoder, writeSyncer, l)

	//5、New方法自定义
	logger := zap.New(core, zap.AddCaller())

	//替换全局，在其他地方zap.L()就能拿到这个zap的实例，不必再返回一个*zap.Logger
	zap.ReplaceGlobals(logger)
	return
}
func getEncoder() zapcore.Encoder {
	encoderConfig := zapcore.EncoderConfig{
		//定义日志的key和value
		LevelKey:    "等级",
		EncodeLevel: zapcore.LowercaseLevelEncoder, //日志等级小写，如果希望大写请使用：zapcore.CapitalLevelEncoder,

		//定义表示日志时间的key和value
		TimeKey:    "时间",
		EncodeTime: zapcore.ISO8601TimeEncoder,

		//定义message的key和value，value是logger.Error等记录日志函数的第一个参数
		MessageKey: "提示信息",

		//定义当前生成这条日志的调用位置的key和value，只有在zap.New(core, zap.AddCaller())中添加第二个参数，才会输出这个字段
		CallerKey:    "调用位置",
		EncodeCaller: zapcore.ShortCallerEncoder, //调用位置从项目根目录开始，如果希望是系统绝对路径请使用：FullCallerEncoder

		//每行以\n结尾
		LineEnding: zapcore.DefaultLineEnding,

		NameKey:       "logger",
		FunctionKey:   zapcore.OmitKey,
		StacktraceKey: "stacktrace",

		EncodeDuration: zapcore.SecondsDurationEncoder,
	}
	return zapcore.NewJSONEncoder(encoderConfig)
}
func getLogWriter(filename string, maxSize, maxBackup, maxAge int, compress bool) zapcore.WriteSyncer {
	lumberJackLogger := lumberjack.Logger{
		Filename:   filename,  //日志文件的位置
		MaxSize:    maxSize,   //日志文件的最大大小（以MB为单位）
		MaxBackups: maxBackup, //保留旧文件的最大个数
		MaxAge:     maxAge,    //保留旧文件的最大天数
		Compress:   compress,  //是否压缩/归档旧文件
	}
	return zapcore.AddSync(&lumberJackLogger)
}

// GinLogger 接收gin框架默认的日志
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		zap.L().Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}

// GinRecovery recover掉项目可能出现的panic，并使用zap记录相关日志
func GinRecovery(stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// Check for a broken connection, as it is not really a
				// condition that warrants a panic stack trace.
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					zap.L().Error(c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					// If the connection is dead, we can't write a status to it.
					c.Error(err.(error)) // nolint: errcheck
					c.Abort()
					return
				}

				if stack {
					zap.L().Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					zap.L().Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				c.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		c.Next()
	}
}
